Kotlin

Sealed Classes

Swift
                  sealed class Expr
​
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
                
                    indirect enum Expr {
    case const(Double)
    case sum(Expr, Expr)
    case notANumber
}

                  

Sealed interfaces

                  sealed interface Expr
​
sealed class MathExpr(): Expr
​
data class Const(val number: Double) : MathExpr()
data class Sum(val e1: Expr, val e2: Expr) : MathExpr()
object NotANumber : Expr
                
                    protocol Expr {}

indirect enum MathExpr: Expr {
    case const(Double)
    case sum(Expr, Expr)
    case notANumber
}

                  

Sealed classes and when expression

                  fun eval(expr: Expr): Double = when(expr) {
    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    NotANumber -> Double.NaN
    // the `else` clause is not required because we've covered all the cases
}
                
                    func eval(expr: Expr) -> Double? {
    switch expr {
    case .const(let number):
        return number
    case .sum(let e1, let e2):
        return eval(e1) + eval(e2)
    default:
        return nil
    }
}

                  

Try sealed interfaces and package-wide hierarchies of sealed classes

                  kotlinOptions.languageVersion = "1.5"